<?php
	$chkAll = $this->formCheckbox('chkAll', 0);
	// Tạo search
	$ssFilter = $this->arrParam['ssFilter'];
	$action_link 	= $this->baseUrl($this->currentController . '/filter/type/order');
	
	if($ssFilter['state'] == 0) {
		$lblDelete = 'Xóa tạm';
		$linkDelete = '';
		$deleteMsg = 'hiện';
	} else {
		$lblDelete = 'Xóa hẵn';
		$linkDelete = '/rm/1';
		$deleteMsg = 'ẩn';
	}
	
	// Tạo tiêu đề dùng để sắp xếp
	$lblId 	= $this->cmsLinkSort('#ID', 'id', $ssFilter, $this->baseUrl(PUBLIC_PATH . '/img/icon'), $action_link);
	$lblTitle = $this->cmsLinkSort('Tiêu đề', 'tieu_de', $ssFilter, $this->baseUrl(PUBLIC_PATH . '/img/icon'), $action_link);
	$lblDes= $this->cmsLinkSort('Mô tả', 'mo_ta', $ssFilter, $this->baseUrl(PUBLIC_PATH . '/img/icon'), $action_link);
	$lblDateCreated= $this->cmsLinkSort('Ngày đăng', 'ngay_dang', $ssFilter, $this->baseUrl(PUBLIC_PATH . '/img/icon'), $action_link);
	//Tool bar
	$linkDisableItems = $this->baseUrl($this->currentController . '/delete' . $linkDelete);
	$btnDisableItems = $this->cmsButton('Xóa nhiều dòng', $linkDisableItems, $this->baseUrl(PUBLIC_PATH . "/img/toolbar/disable_user.png"), 'submit','multidelete');
	//Search
	$state = $this->formSelect('state', $ssFilter['state'], array('style' => 'width:130px; margin-right:5px;'), array(0 => 'Hiển thị', 1 => 'Đã xóa'));
	$keywords = $this->formText('keywords', $ssFilter['keywords'],array('class'=>'span3','placeholder'=>'Tìm kiếm'));
	$linkSearch = $this->baseUrl($this->currentController . '/filter/type/search/key/1');
	$btnSearch = $this->formButton('search-now', 'Search now', array('onclick'=>"OnSubmitForm('" . $linkSearch . "')",'class'=>'btn '));
	$linkResetSearch = $this->baseUrl($this->currentController . '/filter/type/search/key/0');
	$btnResetSearch = $this->formButton('clear-keywords', 'Clear', array('onclick'=>"OnSubmitForm('" . $linkResetSearch . "')",'class'=>'btn'));
	$strSearch = $state . ' ' . $keywords. ' ' . $btnSearch . ' ' . $btnResetSearch;
	
	//filter
	$filterCol=$this->arrParam['ssFilter']['filter_col'];
	$filterVal=$this->arrParam['ssFilter']['filter_val'];
	$stsArr = array('1'=>"Chưa duyệt",'2'=>"Đã duyệt",'3'=>"Yêu cầu thay đổi",'4'=>"Không hợp lệ");
	$option = '<option value="-1">---Tất cả---&nbsp;</option>';
	for ($i = 1; $i < 5; $i++){
		if ($filterCol == "trang_thai" && !empty($filterVal) && $filterVal == $i) {
			$option .= '<option value="'.$i.'" selected>'.$stsArr[$i].'</option>';
		}
		else
		$option .= '<option value="'.$i.'">'.$stsArr[$i].'</option>';
	}
	$statusFilter = '<select class="selectpicker dropup dis-margin" id="stsSlect" data-width="120px">'.$option.'</select>';
?>

<input
	id="msgvalue" type="hidden" value='<?php echo $this->msg;?>' />
<input
	type="hidden" id="sts" name="<?php echo $filterCol;?>"
	value="<?php echo $filterVal;?>" />
<div id="toolbar-box" class="title">
	<div class="top-box">
		<div class="top-box">
			<div class="top-box"></div>
		</div>
	</div>
	<div class="m-box">
		<div class="icon-page title-users"></div>
		<?php echo $btnDisableItems;?>
		<div class="h2">Danh sách tin rao phòng trọ</div>
		<div class="clear"></div>
	</div>
	<div class="bottom-box">
		<div class="bottom-box">
			<div class="bottom-box"></div>
		</div>
	</div>
</div>
<div id="profilemsg" class="alert "></div>
<form
	name="appForm" action="" method="POST">
	<!-- Search btn -->
	<p class="search-box input-append">
	<?php	echo $strSearch; ?>
	</p>
	<!-- Total items label -->
	<div class="total-items">
		<span><?php echo $this->totalItems;?> items</span>
	</div>
	<!-- Main grid -->
	<table class="gridview" id="tinraotb">
		<thead>
			<tr>
				<th class="check-column"><?php echo $chkAll;?></th>
				<th><?php echo $lblId; ?></th>
				<th><?php echo $lblTitle; ?></th>
				<th><?php echo $lblDes; ?></th>
				<th>Loại tin</th>
				<th>Gói tin</th>
				<th><?php echo $lblDateCreated; ?></th>
				<th><?php echo $statusFilter;?></th>
				<th>Thao tác</th>
			</tr>
		</thead>
		<tbody>
		<?php
		$tootipContent ='';
		$overlay ='';
		$modal='';
		$msgmodal='';
		if(count($this->Items) > 0) {
			foreach($this->Items as $key => $val) {
				$id    		 = $val->getId();
				$title       = $val->getTieu_de();
				$description = $val->getMo_ta();
				$userObj     = $val->getNguoiDangObj();
				$loaitin     = $val->getLoaiTinObj();
				$goitin      = $val->getGoiTinObj();
				$loaiphong   = $val->getLoaiPhongObj();
				$ngaydang    = $val->ngay_dang;
				$city        = $val->getThanhPhoObj();
				$district    = $val->getQuanHuyenObj();
				$status      = $val->getTrangThaiStr();
				$nguoi_dang  = $val->getNguoi_dang();
				//Link
				$modalLink	     = 'userModel' . $id;
				$modalMsg	     = 'msgModel' . $id;
				$sendSmgLink     = $this->baseUrl($this->currentController . '/sendmsg/id/' . $id);
				$chkid   	     = $this->formCheckbox('cid[]', $id, array('class' => 'case'));
				$btnView         = '<a class="btn btn-primary btn-mini" href="#'.$modalLink.'" role="button" data-toggle="modal"><i class="icon-eye-open icon-white"></i>Xem</a>';
				$btnSendMsg      = '<a class="btn btn-primary btn-mini" href="#" onclick="sendMSG('.$id.')" role="button" data-toggle="modal"><i class="cus-email_go"></i>&nbsp;</a>';
				$linkChangeSts =array( '0'=>$this->baseUrl($this->currentController . '/changeStatus/id/' . $id.'/newsts/0'),
									   '1'=>$this->baseUrl($this->currentController . '/changeStatus/id/' . $id.'/newsts/1'),
									   '2'=>$this->baseUrl($this->currentController . '/changeStatus/id/' . $id.'/newsts/2'),
									   '3'=>$this->baseUrl($this->currentController . '/changeStatus/id/' . $id.'/newsts/3'));
				$btnActionArr =array(  '0'=>'<li><a class="" href="'.$linkChangeSts[0].'"><i class="cus-new"></i><span>'.$stsArr[1].'</span></a><li>',
									   '1'=>'<li><a class="" href="'.$linkChangeSts[1].'"><i class="cus-accept"></i><span>'.$stsArr[2].'</span></a><li>',
									   '2'=>'<li><a class="" href="'.$linkChangeSts[2].'"><i class="cus-tag_blue_edit"></i><span>'.$stsArr[3].'</span></a><li>',
									   '3'=>'<li><a class="" href="'.$linkChangeSts[3].'"><i class="cus-error_delete"></i><span>'.$stsArr[4].'</span></a><li>',

				);
				$btnAction = '';
				foreach ($btnActionArr as $k=>$value) {
					if ($k!=$val->getTrang_thai()) {
						$btnAction .=$value;
					}
				}
				$action = '';
				if ($val->getTrang_thai() != 1 && $ssFilter['state'] == 0) {
					//Action button
					$action = '<div class="btn-group dropup">
									<button class="btn btn-primary btn-mini" data-toggle="dropdown" >
									<i class="icon-ok-circle icon-white"></i>
									Đổi trạng thái
		    						<button class="btn btn-primary btn-mini dropdown-toggle" data-toggle="dropdown">&nbsp;
	                                <span class="caret"></span>
	                                </button>
		    						<ul class="dropdown-menu">'.$btnAction.'</ul>
				               </div>';
				}
				
				//Action button
				$function = '<div class="btn-group dropup">
								<button class="btn btn-primary btn-mini" data-toggle="dropdown" >
									<i class="icon-ok-circle icon-white"></i>Chức năng
								</button>
		    					<button class="btn btn-primary btn-mini dropdown-toggle" data-toggle="dropdown">&nbsp;
	                               <span class="caret"></span>
	                            </button>
		    					<ul class="dropdown-menu">
				                	<li><a class="" href="#'.$modalLink.'" role="button" data-toggle="modal"><i class="cus-eye"></i>Xem</a></li>
				                	<li><a class="" href="#" onclick="sendMSG('.$id.')" role="button" data-toggle="modal"><i class="cus-email_go"></i>Gửi tin</a></li>
				                	<li><a class="confirm-dialog" onclick="return confirmDialog(this, \'/admin/ptrtinrao/delete' . $linkDelete . '/id/' . $id . '\');" href="#"><i class="cus-bin_closed"></i>' . $lblDelete . '</a></li>
				                </ul>
				           </div>';
					
				$detailinfo ='';
				$detailinfo .= '<div id="tinrao'.$id.'"><table class="dialog_table table table-hover table-bordered">';
				$detailinfo .="<tr class='odd'><th>Tiêu đề:</th><td>".$title."</td></tr>";
				$detailinfo .="<tr class='even'><th>Mô tả:</th><td>".$description."</td></tr>";
				$detailinfo .="<tr class='even'><th>Địa chỉ:</th><td>".$val->getDia_chi()."</td></tr>";
				$detailinfo .="<tr class='even'><th>Quận huyện - TP:</th><td>".$district->getTen()." - ".$city->getTen()."</td></tr>";
				$detailinfo .="<tr class='odd'><th>Loại tin:</th><td>".$loaitin->getTen()."</td></tr>";
				$detailinfo .="<tr class='even'><th>Gói tin:</th><td>".$goitin->getTen()."</td></tr>";
				$detailinfo .="<tr class='odd'><th>Loại phòng:</th><td>".$loaiphong->getTen()."</td></tr>";
				$detailinfo .="<tr class='even'><th>Ngày đăng:</th><td>".$ngaydang."</td></tr>";
				$detailinfo .= "</table></div>";

				$modal .='<div id="'.$modalLink.'" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  							<div class="modal-header">
						    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
						    <h4 id="myModalLabel">Thông tin chi tiết tin rao <span>'.$id.'</span></h4>
						  	</div>
						  	<div class="modal-body">'.
				$detailinfo.
						  	'</div>
						  	<div class="modal-footer" style="text-align: left;">
									'.$action .'		
							</div>
							</div>';
				
				echo '<tr id='.$id.'>';
				echo '<th class="check-column" scope="row">'.$chkid.'</th>';
				echo '<td>'.$id.'</td>';
				echo '<td title="'.$title.'">'.Zendhlt_Utilities_Utils::substrwords($title, 25).'</td>';
				echo '<td title="'.$description.'">'.Zendhlt_Utilities_Utils::substrwords($description, 30) .'</td>';
				echo '<td>'.$loaitin->getTen().'</td>';
				echo '<td>'.$goitin->getTen().'</td>';
				echo '<td>'.$ngaydang.'</td>';
				echo '<td>'.$status.'</td>';
				echo '<td> '.$action.'  ' .$function.'</td>';

			}
		} else {
		?>
				<tr><td colspan="9" align="center">Không có dữ liệu.</td></tr>
		<?php
			}
		?>

		</tbody>
		
		<!-- BEGIN: PAGINATION (FOOT) -->
		<tfoot>
			<tr>
				<td colspan="9">
					<div class="container">
						<div class="pagination">
						<?php
						$currentUrl = $this->baseUrl($this->currentController . '/index');
						echo $this->paginationControl($this->panigator, 'Sliding', 'pagination.phtml', array('currentUrl' => $currentUrl));
						?>
							<div class="limit"></div>
						</div>
					</div>
				</td>
			</tr>
		</tfoot>
		<!-- END: PAGINATION (FOOT) -->
	</table>
	
</form>
<div class="dialog" id="question">
	<img src="<?php echo $this->baseUrl(PUBLIC_PATH . '/img/question.png'); ?>" alt="question" />
	<p>Bạn có chắc chắn muốn <?php echo $lblDelete; ?> không?</p>
</div>

<?php
	echo $modal;
	//Send msg form
	$msgform = new Admin_Form_SendMsg();
	$msgform->setName("sendmsgform");
	$msgform->addHid('ptr_tin_rao',0);
	$msgmodal='<div id="sendMsgModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="msgmodal" aria-hidden="true">
  				<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				<h4 id="myModalLabel">Gửi tin nhắn cho người đăng <span></span></h4>
				</div>
				<div class="modal-body">
				<div id="sendmsgalert" class="alert "></div>
				'. $msgform.'
				</div>
				
				</div>';
	echo $msgmodal;					
						
?>

<script type="text/javascript">

	$("a.confirm-dialog").click(function(event){
		$( "#question" ).dialog("open");
	});
	
	// add multiple select / deselect functionality
    $("#chkAll").click(function () {
          $('.case').attr('checked', this.checked);
    });
    
    // if all checkbox are selected, check the selectall checkbox and viceversa
    $(".case").click(function() {
        if($(".case").length == $(".case:checked").length) {
            $("#chkAll").attr("checked", "checked");
        } else {
            $("#chkAll").removeAttr("checked");
        }
    });
    
	$('.selectpicker').selectpicker({
		style: 'btn',
		size: 5
	});
    $('#stsSlect').change(function(){
        stsFilter();
 	});
    $('#state').change(function(){
    	stateFilter();
 	});

	$(function() {
		//Result message
		if($('#msgvalue').val() == '' || $('#msgvalue').val() == null){
			$('#profilemsg').hide();
		} else {
			$('#profilemsg').show();
		}
		setTimeout(function() { 
	        $('#profilemsg').fadeOut();
		}, 5000); 
	
		//Send MSG
		var isProcessing = false;
		$('#sendMsgModal').find("#submitbutton").click(function(event) {
			if (confirm("Bạn có chắc muốn gửi tin nhắn này?")) {
				if(isProcessing){
					return;
				}
				var url = '/admin/message/sendajax';
				var data = {};
				data['tieu_de']=$.trim($('#sendMsgModal').find('#tieu_de').val());
				data['noi_dung']=$.trim($('#sendMsgModal').find('#noi_dung').val());
				data['ptr_tin_rao']=$.trim($('#sendMsgModal').find('#ptr_tin_rao').val());
				if(!data['tieu_de']||!data['noi_dung']){
					doValidation('tieu_de');
					doValidation('noi_dung');
					isProcessing = false;
				} else {
					isProcessing = true;
					$('#sendMsgModal').find("#submitbutton").attr("disabled", "disabled");
					$.post(url, data, function(resp) {
						if(resp.sts == "OK") {
							$('#sendMsgModal').find('#sendmsgalert').html("Gửi tin nhắn thành công!");
							$('#sendMsgModal').find('#sendmsgalert').show();
						} else {
							$('#sendMsgModal').find('#sendmsgalert').html("Xảy ra lỗi trong quá trình gửi tin nhắn!");
							$('#sendmsgalert').show();
						}
						setTimeout(function() { 
							$('#sendMsgModal').hide();}, 5000); 
						isProcessing = false;
					}, 'json');
				}
			}
		});
	});
	
	function stsFilter() {
	    var filterVal = $("#stsSlect").val();
	    if (filterVal > -1) {
	    	document.appForm.action = '/admin/ptrtinrao/filter/type/filter/filter_col/trang_thai/filter_val/'+filterVal;
	        document.appForm.submit();
		} else {
			document.appForm.action = '/admin/ptrtinrao/filter/type/search/key/0';
	        document.appForm.submit();
		}
	}
	
	function stateFilter() {
	    var filterVal = $("#state").val();
    	document.appForm.action = '/admin/ptrtinrao/filter/type/state/state/'+filterVal;
        document.appForm.submit();
	}

	$(function() {
		$('#sendMsgModal').find('#tieu_de').blur(function() {
			doValidation('tieu_de');
		});
		$('#sendMsgModal').find('#noi_dung').blur(function() {
			doValidation('noi_dung');
		});
	});
	
	function doValidation(id) {
	    var url = '/admin/message/validate';
	    var data = {};
	    $('#sendMsgModal').find("textarea").each(function() {
	        data[$(this).attr('name')] = $(this).val();
	    });
	    $.post(url, data, function(resp) {
	    	$('#sendMsgModal').find("#" + id).parent().find('.errors').remove();
	    	$('#sendMsgModal').find("#" + id).parent().append(getErrorHtml(resp[id], id));
	    }, 'json');
	}
	
	function getErrorHtml(formErrors , id) {
	    var o = '<ul id="errors-'+ id +'" class="errors">';
	    if(formErrors){
		    if (formErrors.length == undefined) {
			    for(errorKey in formErrors) {
			   		o += '<li>' + formErrors[errorKey] + '</li>';
			    }
		    } else {
		    	o += '<li>' + formErrors + '</li>';
		    }
		    o += '</ul>';
		    return o;
	    }
	}
	
	function sendMSG(id) {
	
		$('#sendMsgModal').find('#tieu_de').parent().find('.errors').remove();
		$('#sendMsgModal').find('#noi_dung').parent().find('.errors').remove();
		$('#sendMsgModal').find('#ptr_tin_rao').val(id);
		$('#sendMsgModal').find('#tieu_de').val(null);
		$('#sendMsgModal').find('#noi_dung').val(null);
		$('#sendMsgModal').find('#sendmsgalert').hide();
		$('#sendMsgModal').find("#submitbutton").show();
		$('#sendMsgModal').find("#submitbutton").removeAttr("disabled");
		$('#sendMsgModal').modal();
	}
</script>
